package com.qidian.tcba.oss.api;


import com.qidian.tcba.oss.model.dto.AttachmentResultDTO;
import com.qidian.tcba.oss.service.AttachmentsService;
import com.qidian.tcba.utils.BusinessException;
import com.qidian.tcba.utils.Message;
import com.qidian.tcba.utils.result.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/oss")
@Api(tags = "文件")
public class AttachController {

    private final AttachmentsService attachmentService;

    public AttachController(AttachmentsService attachmentService) {
        this.attachmentService = attachmentService;
    }


    @ApiOperation("单文件上传")
    @PostMapping("/upload/{ownerType}/{ownerId}/{businessType}")
    public JsonResult upload( MultipartFile file,
                              @PathVariable("ownerType") int ownerType,
                              @PathVariable("ownerId")int ownerId,
                              @PathVariable("businessType")int businessType) throws IOException {
        AttachmentResultDTO upload = attachmentService.upload(file,ownerType,ownerId,businessType);
        return JsonResult.success().data("row", upload);
    }

    @ApiOperation("多文件上传")
    @PostMapping("/uploadBatches/{ownerType}/{ownerId}/{businessType}")
    public JsonResult uploadBatch(MultipartFile[] files,
                                  @PathVariable("ownerType") int ownerType,
                                  @PathVariable("ownerId")int ownerId,
                                  @PathVariable("businessType")int businessType) {
        List<AttachmentResultDTO> attachResultDTOS = attachmentService.uploadBatch(files,ownerType, ownerId, businessType);
        return JsonResult.success().data("rows", attachResultDTOS);
    }

    @ApiOperation("获取包的地址")
    @GetMapping("/download/{ownerType}/{ownerId}/{businessType}")
    public JsonResult download(@PathVariable("ownerType") int ownerType,
                               @PathVariable("ownerId")int ownerId,
                               @PathVariable("businessType")int businessType) {
        List<String> urls = attachmentService.getPath(ownerType, ownerId,businessType);
        return JsonResult.success().data("rows",urls);
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/removeById/{id}")
    public JsonResult removeById(@PathVariable("id") int id) {
        boolean removed = attachmentService.removeById(id);
        if(!removed) {
            throw new BusinessException(new Message("DB.DELETE_FAILED","文件"));
        }
        return JsonResult.success().msg(new Message("DB.DELETE_SUCCESS"));
    }
}
